/*
 * @Author: liaoxin
 * @email: 2858765077@qq.com
 * @FilePath: \personnelmanage\src\pages\QuotaManage\Report\StockDetailReport\index.tsx
 * @Date: 2022-11-04 09:59:32
 * @LastEditTime: 2022-11-07 14:55:38
 */
// 库存明细报表
import * as React from 'react'
import { useEffect, useState } from 'react'
import moment from 'moment'
import { http } from '@/lib'
import apis from '@/apis/Report'
import './index.scss'
import { Form, Col, Row, Input, DatePicker, Button, Table, Select, message, Spin } from 'antd'
import { downBlobFile } from '@/utils/methods'
import { toDateString } from '../helper'
const { RangePicker } = DatePicker
const { Option } = Select
// 搜索框
function SearchBar(props) {
  // 修改父组件中的table源数据的方法
  const { changeFatherDataSource } = props
  // 搜索框内的值
  const [searchValue, setSearchValue] = useState(props.searchValue)
  // 导出和查询数据时候的等待状态
  const [exportLoading, setExportLoading] = useState(false)
  // 表单点击查询时候执行的方法
  const onSubmit = e => {
    e.preventDefault()
    changeFatherDataSource(searchValue)
  }
  const [mode, setMode] = useState(['date', 'date'])
  // 保存销售组织列表
  const [brandList, setBrandList] = useState<any>([])
  // 获取品牌组织
  useEffect(() => {
    let UaaSysInfo = JSON.parse(sessionStorage.getItem('UaaSysInfo'))
    setBrandList(UaaSysInfo.profile.brandList)
  }, [])

  return (
    <div style={{ border: '1px solid #eee', padding: '18px 22px 0px 8px' }}>
      <Form layout="inline" name="formValue" onSubmit={onSubmit}>
        <Row style={{ height: '60px' }}>
          <Col offset={1} span={6}>
            <Form.Item label="销售组织">
              <Select
                placeholder="请选择销售组织"
                onChange={(values: any) => {
                  setSearchValue({ ...searchValue, brandCode: values })
                }}
                style={{ width: '174px', display: 'inline-block', color: searchValue.brandCode == '' ? '#ccc' : '' }}
                allowClear={true}
                dropdownMatchSelectWidth={false}
                value={searchValue.brandCode != '' ? searchValue.brandCode : '请选择销售组织'}
              >
                {brandList.map(({ brandCode, brandName }) => (
                  <Option style={{ width: '250px' }} key={brandCode} value={brandCode}>
                    {brandName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col offset={1} span={6}>
            <Form.Item label="客户编码">
              <Input
                placeholder="请输入"
                value={searchValue.dealerCode}
                onChange={e => {
                  setSearchValue({ ...searchValue, dealerCode: e.target.value })
                }}
              />
            </Form.Item>
          </Col>
          <Col offset={1} span={6}>
            <Form.Item label="客户名称">
              <Input
                placeholder="请输入"
                value={searchValue.dealerName}
                onChange={e => {
                  setSearchValue({ ...searchValue, dealerName: e.target.value })
                }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row style={{ height: '60px' }}>
          <Col offset={1} span={6}>
            <Form.Item label="盘点周期">
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                value={searchValue.checkTime}
                mode={mode}
                onChange={value => {
                  setSearchValue({ ...searchValue, checkTime: value || [] })
                }}
                onOpenChange={status => {
                  if (status) {
                    setSearchValue({ ...searchValue, checkTime: [] })
                  }
                }}
                // onPanelChange={(value, mode) => {
                //   // 判断选择的日期是否超过了今天
                //   if ((value[0] as any) > moment.now() || (value[1] as any) > moment.now()) {
                //     message.warn('选择的日期不能超过当月')
                //   } else {
                //     setSearchValue({ ...searchValue, checkTime: value || [] })
                //     // setMode([mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]])
                //   }
                // }}
                style={{ width: '174px' }}
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Col>
          <Col offset={1} span={6}>
            <Form.Item label="物料名称">
              <Input
                placeholder="请输入"
                value={searchValue.matName}
                onChange={e => {
                  setSearchValue({ ...searchValue, matName: e.target.value })
                }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row
          align="middle"
          justify="space-around"
          gutter={24}
          style={{
            marginTop: '20px',
            borderTop: '1px solid #eee',
            borderBottom: '1px solid #eee',
            paddingTop: '4px',
            paddingBottom: '4px',
          }}
        >
          <Col offset={10} span={14}>
            <Button htmlType="submit" type="primary" loading={exportLoading} style={{ marginRight: '20px' }}>
              查询
            </Button>
            <Button
              type="default"
              onClick={() => {
                setSearchValue({
                  // 销售组织
                  brandCode: '',
                  // 管理区域
                  belongAreaName: '',
                  // 盘点周期
                  checkTime: [],
                  // 客户编码
                  dealerCode: '',
                  // 客户名称
                  dealerName: '',
                  // 物料编码
                  // prodBarcode: '',
                  // 物料名称
                  matName: '',
                })
              }}
              loading={exportLoading}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

const StockDetailReport = () => {
  const TableTitleStyle = {} as any
  // table的数据源
  const [dataSource, setDataSource] = useState<any>([])
  // table的列标题
  const columns = [
    {
      title: <span style={TableTitleStyle}>序号</span>,
      key: 'number',
      render: (text, record, index) => {
        return <span>{(pagination.current - 1) * pagination.pageSize + index + 1}</span>
      },
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>销售组织</span>,
      key: 'brandName',
      dataIndex: 'brandName',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>管理区域</span>,
      key: 'belongAreaName',
      dataIndex: 'belongAreaName',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>盘点周期</span>,
      key: 'description',
      dataIndex: 'description',
      align: 'center',
      // render: text => {
      //   let year = text.split(' ')[0].split('-')[0]
      //   let month = parseInt(text.split(' ')[0].split('-')[1])
      //   return <span>{year + '年' + month + '月'}</span>
      // },
    },
    {
      title: <span style={TableTitleStyle}>客户编码</span>,
      key: 'dealerCode',
      dataIndex: 'dealerCode',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>客户名称</span>,
      key: 'dealerName',
      dataIndex: 'dealerName',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>客户地址</span>,
      key: 'address',
      dataIndex: 'address',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>盘点客户名称</span>,
      key: 'checkDealerName',
      dataIndex: 'checkDealerName',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>盘点客户编码</span>,
      key: 'checkDealerCode',
      dataIndex: 'checkDealerCode',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>物料编码</span>,
      key: 'prodBarcode',
      dataIndex: 'prodBarcode',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>物料描述</span>,
      key: 'matName',
      dataIndex: 'matName',
      align: 'center',
    },
    {
      title: <span style={TableTitleStyle}>期初库存（含未到货）/件</span>,
      key: 'beginningRealStock',
      dataIndex: 'beginningRealStock',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>期间开单/件</span>,
      key: 'nowAog',
      dataIndex: 'nowAog',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>调货/件</span>,
      key: 'allocateNumber',
      dataIndex: 'allocateNumber',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>期末实物库存/件</span>,
      key: 'nowRealStock',
      dataIndex: 'nowRealStock',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>期末未到货/件</span>,
      key: 'onOrder',
      dataIndex: 'onOrder',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>期间动销数/件</span>,
      key: 'nowMove',
      dataIndex: 'nowMove',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>下月订单计划/件</span>,
      key: 'nextMonthOrderNum',
      dataIndex: 'nextMonthOrderNum',
      align: 'center',
      render: text => (text === null ? '--' : text),
    },
    {
      title: <span style={TableTitleStyle}>备注</span>,
      key: 'remark',
      dataIndex: 'remark',
      align: 'center',
    },
  ]
  const [searchValue, setSearchValue] = useState({
    // 销售组织
    brandCode: '',
    // 管理区域
    belongAreaName: '',
    // 盘点周期 -> 盘点开始时间inventoryBegineTime  盘点结束时间inventoryEndTime
    checkTime: [],
    // 客户(经销商)编码
    dealerCode: '',
    // 客户(经销商)名称
    dealerName: '',
    // 物料编码
    // prodBarcode: '',
    // 物料名称
    matName: '',
  })
  const [pagination, setPagination] = useState({
    page: 1,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '40', '60', '100', '150', '200'],
    total: 0,
    showTotal: (total, range) => `共 ${total} 条记录 当前${range[0]} / ${range[1]} `,
  })
  // table的loading
  const [loading, setLoading] = useState(false)
  const [search, setSearch] = useState(false)
  const [firstCome, setFirstCome] = useState(true)
  // 加载页面获取数据
  useEffect(() => {
    if (!firstCome) {
      setLoading(true)
      let request: any = {
        page: pagination.page,
        size: pagination.pageSize,
      }
      for (let key in searchValue) {
        if (searchValue[key] && key != 'checkTime') {
          if (key === 'dealerCode') {
            request['dealerCodes'] = searchValue[key]
          } else {
            request[key] = searchValue[key]
          }
        }
      }
      if (searchValue['checkTime'].length > 0) {
        request.inventoryBegineTime = `${searchValue.checkTime[0].format('YYYY-MM-DD')} 00:00:00`
        request.inventoryEndTime = `${searchValue.checkTime[1].format('YYYY-MM-DD')} 23:59:59`
      }
      http
        .post(apis.ReportStock, request)
        .then(res => {
          let data = res.data.content
          setDataSource(data)
          setPagination({ ...pagination, total: res.data.totalElements })
          setExportLoading(false)
          setLoading(false)
        })
        .catch(() => {
          // console.log(err);
          setExportLoading(false)
          setLoading(false)
        })
    }
    firstCome && setFirstCome(false)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.page, pagination.pageSize, search])
  // 修改table的datasouce的方法
  const changeFatherDataSource = searchV => {
    setLoading(true)
    // setDataSource(value);
    setSearchValue(searchV)
    if (pagination.page === 1) {
      setSearch(!search)
    }
    setPagination({ ...pagination, page: 1, current: 1 })
    setLoading(false)
  }
  // 导出和查询数据时候的等待状态
  const [exportLoading, setExportLoading] = useState(false)
  // 导出excel表格的方法
  const exportExcel = () => {
    if (searchValue.checkTime.length === 0) {
      message.warn('请选择盘点周期')
      return
    }

    if (pagination.total >= 30000) {
      message.error('数据超载不能导出，请重新筛选缩小数据范围')
      return
    }
    setExportLoading(true)
    message.warn('导出中....请稍等')
    let url: string = ''
    let fileName: string = ''
    let param: string = `?page=${1}&size=${30000}`
    for (let key in searchValue) {
      if (searchValue[key] && !(searchValue[key] instanceof Array) && key !== 'dealerCode') {
        param += `&${key}=${searchValue[key]}`
      } else if (searchValue[key] instanceof Array && searchValue[key].length > 0 && key !== 'dealerCode') {
        let start = `${searchValue.checkTime[0].format('YYYY-MM-DD')} 00:00:00`
        let end = `${searchValue.checkTime[1].format('YYYY-MM-DD')} 23:59:59`
        param += `&inventoryBegineTime=${start}&inventoryEndTime=${end}`
      }
    }
    if (searchValue['dealerCode']) {
      param += `&dealerCodes=${searchValue['dealerCode']}`
    }
    url = apis.ExportExcelReportStock
    fileName = '库存明细报表'
    http
      .get(url + param, { responseType: 'arraybuffer', timeout: 1000 * 60 * 10 * 1000 })
      .then(res => {
        downBlobFile(res.data, fileName)
        setExportLoading(false)
        message.success('导出成功')
      })
      .catch(() => {
        setExportLoading(false)
        message.error('导出失败')
      })
  }
  return (
    <React.Fragment>
      <div className="StockDetailReport-title">库存明细报表</div>
      <SearchBar
        changeFatherDataSource={changeFatherDataSource}
        page={pagination.page}
        size={pagination.pageSize}
        searchValue={searchValue}
      />
      <Row>
        <Col>
          <Button
            type="primary"
            style={{ marginBottom: '10px', marginTop: '10px' }}
            loading={exportLoading}
            onClick={() => {
              exportExcel()
            }}
          >
            导出
          </Button>
        </Col>
      </Row>
      <Spin spinning={loading}>
        <Table
          // loading={loading}
          columns={columns as any}
          pagination={pagination}
          dataSource={dataSource}
          onChange={pageOptions => {
            setPagination({
              ...pagination,
              pageSize: pageOptions.pageSize,
              current: pageOptions.current,
              page: pageOptions.current,
            })
          }}
        />
      </Spin>
    </React.Fragment>
  )
}

export default StockDetailReport
